<template>
  <div class="branch-container">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <el-input
          v-model="data.branchName"
          placeholder="请输入支部名称查询"
          class="search-input"
          :prefix-icon="Search"
      />
      <el-button type="danger" plain @click="load()">查询</el-button>
      <el-button type="danger" plain @click="reset">重置</el-button>
    </div>

    <!-- 数据表格卡片 -->
    <div class="data-card">
      <div class="button-group">
        <el-button type="danger" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增支部
        </el-button>
        <el-button type="danger" plain @click="delBatch">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </div>

      <el-table
          :data="data.tableData"
          max-height="400"
          stripe
          @selection-change="handleSelectionChange"
          style="width: 100%"
      >
        <el-table-column type="selection" width="45" align="center" fixed="left" />
        <el-table-column prop="branchName" label="支部名称" />
        <el-table-column prop="orgType" label="组织类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.orgType === 1 ? 'danger' : scope.row.orgType === 2 ? 'warning' : 'success'">
              {{ scope.row.orgType === 1 ? '校团支部' : scope.row.orgType === 2 ? '院团支部' : '班团支部' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="parentBranchName" label="上级支部"  />
        <el-table-column prop="leaderName" label="支部书记"  />
        <el-table-column prop="description" label="支部描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button size="default" type="danger" @click="handleEdit(scope.row)"  >编辑</el-button>
            <el-button size="default" type="danger" plain @click="del(scope.row.id)"  >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNum"
            :page-sizes="[5, 10, 20, 30, 50]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>

    <!-- 支部表单对话框 -->
    <el-dialog
        :title="data.form.id ? '编辑支部' : '新增支部'"
        v-model="data.formVisible"
        width="600px"
        destroy-on-close
    >
      <el-form
          :model="data.form"
          :rules="rules"
          ref="branchRef"
          label-width="100px"
      >
        <!-- 支部名称 -->
        <el-form-item label="支部名称" prop="branchName">
          <el-input v-model="data.form.branchName" placeholder="请输入支部名称" />
        </el-form-item>

        <!-- 组织类型 -->
        <el-form-item label="组织类型" prop="orgType">
          <el-radio-group v-model="data.form.orgType">
            <el-radio :label="1">校团支部</el-radio>
            <el-radio :label="2">院团支部</el-radio>
            <el-radio :label="3">班团支部</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 上级支部 -->
        <el-form-item label="上级支部" prop="parentId" v-if="data.form.orgType !== 1">
          <el-select
              v-model="data.form.parentId"
              placeholder="请选择上级支部"
              clearable
              filterable
              :filter-method="filterParentOptions"
              :remote="false"
              :loading="data.loading"
          >
            <el-option
                v-for="item in data.filteredParentOptions"
                :key="item.id"
                :label="item.branchName"
                :value="item.id"
            >
              <span style="float: left">{{ item.branchName }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 支部书记 -->
        <el-form-item label="支部书记" prop="userId">
          <el-select
              v-model="data.form.leaderName"
              filterable
              remote
              :remote-method="handleUserSearch"
              :loading="data.userLoading"
              placeholder="请输入姓名搜索"
              @change="handleUserChange"
              clearable
              value-key="id"
          >
            <el-option
                v-for="item in data.userOptions"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.realName }}</span>
                <span style="color: #8492a6; font-size: 13px">
              {{ item.userType === 5 ? '学生' : '其他' }}
            </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 支部描述 -->
        <el-form-item label="支部描述" prop="description">
          <el-input
              v-model="data.form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入支部描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="danger" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import {getUserInfo} from "@/utils/auth";

// 定义响应式数据
const data = reactive({
  branchName: '',
  tableData: [],
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  form: {},
  multipleSelection: [],
  ids: [],
  parentOptions: [],
  user: getUserInfo() ||  {},
  userLoading: false,
  userOptions: [],
  filteredParentOptions: [], // 过滤后的选项
  filteredLeaderOptions: [],
  loading: false, // 加载状态
  leaderId: '', // 支部领导人
})

// 表单验证规则
const rules = {
  branchName: [{ required: true, message: '请输入支部名称', trigger: 'blur' }],
  orgType: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入支部描述', trigger: 'blur' }],
  leaderName: [{ required: true, message: '请输入对应的用户账户', trigger: 'blur' }],
}

// 加载数据
const load = () => {
  request.get('/organizationBranch/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      branchName: data.branchName,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  })
}

// 添加过滤方法
const filterParentOptions = (query) => {
  if (query) {
    // 过滤逻辑
    data.filteredParentOptions = data.parentOptions.filter(item => {
      return item.branchName.toLowerCase().includes(query.toLowerCase())
    })
  } else {
    // 没有搜索词时显示全部
    data.filteredParentOptions = data.parentOptions
  }
}

// 加载上级支部选项
const loadParentOptions = () => {
  data.loading = true
  request.get('/organizationBranch/selectAll', {
    params: {
      //orgType: data.user.userType === 1 ? 1 : 2
    }
  }).then(res => {
    if (res.code === '200') {
      data.parentOptions = res.data
      data.filteredParentOptions = res.data // 初始化过滤后的选项
    }
  }).finally(() => {
    data.loading = false
  })
}

// 新增按钮点击
const handleAdd = () => {
  data.form = {
    orgType: data.user.userType,
    branchName: '',
    parentId: null,
    description: '',
    leaderId: '',
  }
  loadParentOptions()
  data.formVisible = true
}

// 编辑按钮点击
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  loadParentOptions()
  data.formVisible = true
}

// 保存数据
const save = () => {
  const url = data.form.id ? '/organizationBranch/update' : '/organizationBranch/add'
  const method = data.form.id ? 'PUT' : 'POST'

  data.form.leaderId = data.form.leaderName;
  request({
    url,
    method,
    data: data.form
  }).then(res => {
    if (res.code === '200') {
      ElMessage.success('保存成功')
      request.put('/sysUser/update', {
          id: data.form.leaderId,
          userType: data.form.orgType,
        })

      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  })
}

// 删除单条数据
const del = (id) => {
  ElMessageBox.confirm('确定要删除这个支部吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/organizationBranch/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  })
}

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择要删除的支部')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${data.ids.length} 个支部吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/organizationBranch/delete/batch', {
      data: data.ids
    }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '批量删除失败')
      }
    })
  })
}

// 表格多选
const handleSelectionChange = (selection) => {
  data.multipleSelection = selection
  data.ids = selection.map(item => item.id)
}

// 重置搜索条件
const reset = () => {
  data.branchName = ''
  load()
}

// 分页大小改变
const handleSizeChange = (val) => {
  data.pageSize = val
  load()
}

// 当前页改变
const handleCurrentChange = (val) => {
  data.pageNum = val
  load()
}

// 表单引用
const branchRef = ref()

// 提交表单
const submitForm = () => {
  branchRef.value.validate((valid) => {
    if (valid) {
      save()
    } else {
      ElMessage.error('请填写必填项')
      return false
    }
  })
}

// 搜索用户
const handleUserSearch = async (query) => {
  if (!query) return
  data.userLoading = true
  try {
    const res = await request.get('/sysUser/search', {
      params: {
        realName: query,
        userTypes: '1,2,3,4,5'  // 改为逗号分隔的字符串
      }
    })
    if (res.code === '200') {
      data.userOptions = res.data
    }
  } finally {
    data.userLoading = false
  }
}

// 用户选择改变
const handleUserChange = async (userId) => {
  if (!userId) {
    data.selectedUser = null
    data.studentInfo = null
    return
  }
  // 获取用户详情
  const res = await request.get(`/sysUser/${userId}`)
  if (res.code === '200') {
    // 修正数据解构方式
    data.selectedUser = res.data.sysUser
    data.studentInfo = res.data.studentInfo
  }
}

// 初始化
onMounted(() => {
  load()
})
</script>

<style scoped>
.branch-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

.search-card,
.data-card {
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.data-card {
  overflow: hidden;
}

.search-card {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.button-group {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* Element Plus 主题定制 */
:deep(.el-form-item__content),
:deep(.el-date-picker) {
  width: 100%;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 60px;
}

:deep(.el-table) {
  --el-table-header-bg-color: #fff5f5;
  width: 100% !important;
}

:deep(.el-table__body-wrapper) {
  overflow-x: hidden !important;
}

:deep(.el-button--danger) {
  --el-button-bg-color: #c8161d;
  --el-button-border-color: #c8161d;
  --el-button-hover-bg-color: #e54b4b;
  --el-button-hover-border-color: #e54b4b;
  --el-button-active-bg-color: #c8161d;
  --el-button-active-border-color: #c8161d;
  --el-button-text-color: #fff;
}

:deep(.el-button--danger.is-plain) {
  --el-button-bg-color: #fff;
  --el-button-border-color: #c8161d;
  --el-button-text-color: #c8161d;
  --el-button-hover-text-color: #c8161d;
  --el-button-hover-bg-color: #fff5f5;
  --el-button-hover-border-color: #e54b4b;
  --el-button-active-bg-color: #fff5f5;
  --el-button-active-text-color: #c8161d;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #c8161d;
}
</style>
